#!/usr/bin/perl -w

$XDG_CFG="/etc/xdg/menus/arch-applications.menu";
$CACHE_DIR="/var/cache/xdg-menu";
$LOG_FILE="/var/log/update-menus.log";

sub get_cache_dir
{
    my $ret;
    if($ENV{XDG_CACHE_HOME})
    {
        $ret = "$ENV{XDG_CACHE_HOME}/xdg_menu";
    }
    else
    {
        $ret = "$ENV{HOME}/.xdg_menu_cache";
    }
    return $ret;
}

my $cachedir = get_cache_dir;

system("rm -rf $cachedir");
(system("rm -rf $CACHE_DIR/*") == 0) || die("Cannot purge cache!");

open(FH, "</etc/update-menus.conf") || die("No config file!");

while(<FH>)
{
    chomp;
    if(/^icewm$/)
    {
	# icewm
	print "Generating icewm\n";
	mkdir("$CACHE_DIR/icewm") && system("xdg_menu --format icewm --root-menu $XDG_CFG >$CACHE_DIR/icewm/programs 2>>$LOG_FILE");
    }
    elsif(/^ion3$/)
    {
	# ion3
	print "Generating ion3\n";
	mkdir("$CACHE_DIR/ion3") && system("xdg_menu --format ion3  --root-menu $XDG_CFG >$CACHE_DIR/ion3/xdg-menu.lua 2>>$LOG_FILE");
    }
    elsif(/^twm$/)
    {
	# twm
	print "Generating twm\n";
	mkdir("$CACHE_DIR/twm") && system("cp /etc/X11/twm/system.twmrc $CACHE_DIR/twm/twmrc && xdg_menu --format twm  --root-menu $XDG_CFG >>$CACHE_DIR/twm/twmrc 2>>$LOG_FILE");
    }
    elsif(/^WindowMaker$/)
    {
	# WindowMaker
	print "Generating WindowMaker\n";
	mkdir("$CACHE_DIR/WindowMaker") && system("xdg_menu --format WindowMaker --root-menu $XDG_CFG >$CACHE_DIR/WindowMaker/wmrc 2>>$LOG_FILE");
    }
    elsif(/^fvwm2$/)
    {
	# fvwm2
	print "Generating fvwm2\n";
	mkdir("$CACHE_DIR/fvwm2") && system("xdg_menu --format fvwm2 --root-menu $XDG_CFG >$CACHE_DIR/fvwm2/fvwm2rc 2>>$LOG_FILE");
    }
    elsif(/^blackbox$/)
    {
	# blackbox
	print "Generating blackbox\n";
	mkdir("$CACHE_DIR/blackbox") && system("xdg_menu --format blackbox --root-menu $XDG_CFG >$CACHE_DIR/blackbox/boxrc 2>>$LOG_FILE");
    }
    elsif(/^fluxbox$/)
    {
	# fluxbox
	print "Generating fluxbox\n";
	mkdir("$CACHE_DIR/fluxbox") && system("xdg_menu --format fluxbox --root-menu $XDG_CFG >$CACHE_DIR/fluxbox/boxrc 2>>$LOG_FILE");
    }
    elsif(/^openbox$/)
    {
	# openbox
	print "Generating openbox\n";
	mkdir("$CACHE_DIR/openbox") && system("xdg_menu --format openbox3-pipe --root-menu $XDG_CFG >$CACHE_DIR/openbox/menu.xml 2>>$LOG_FILE");
    }
    elsif(/^jwm$/)
    {
	# jwm
	print "Generating jwm\n";
	mkdir("$CACHE_DIR/jwm") && system("xdg_menu --format jwm --fullmenu --root-menu $XDG_CFG >$CACHE_DIR/jwm/menu.xml 2>>$LOG_FILE");
    }
    elsif(/^#.*$/)
    {
    }
    else
    {
	print "Unknown line: $_\n";
    }
}

close FH;
